using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace M13.Math
{
    public static class M13Mathf
    {
        public static int XZYToIndex(Vector3Int xyz)
        {
            if (xyz.x > 15 || xyz.z > 15) throw new System.Exception("错误参数");
            return (xyz.x << 10) + (xyz.z << 6) + xyz.y;
        }

        public static Vector3Int IndexToXZY(int index)
        {
            int x = index >> 10;
            int z = (index - (x << 10)) >> 6;
            int y = index - (z << 6) - (x << 10);
            return new Vector3Int(x, y, z);
        }

        public static int XYToIndex(Vector2Int xy)
        {
            if (xy.x > 15 || xy.y > 15) throw new System.Exception("错误参数");
            return (xy.x << 4) + xy.y;
        }

        public static Vector2Int IndexToXY(int index)
        {
            if (index > 255) throw new System.Exception("错误参数");
            return new Vector2Int(index >> 4, index - ((index >> 4) << 4));
        }

        public static Vector2Int ChunkToRegionCoord(Vector2Int chunkLocalCoord)
        {
            return new Vector2Int(chunkLocalCoord.x >> 4, chunkLocalCoord.y >> 4);
        }

        public static int ChunkIndexOnRegion(Vector2Int chunkLocalCoord)
        {
            Vector2Int regionCoord = ChunkToRegionCoord(chunkLocalCoord);
            Vector2Int v = chunkLocalCoord - regionCoord * 16;
            return M13Mathf.XYToIndex(v);
        }

        public static int CalculateManhattanDistence(Vector2Int pos1, Vector2Int pos2)
        {
            return (int)(MathF.Abs(pos1.x - pos2.x) + MathF.Abs(pos1.y - pos2.y));
        }
    }
}